﻿#include "WRWorkDeviceCollection.h"

#include "WRWorkDriver.h"
#include "WRWorkDevice.h"

#include <QList>
#include <QHash>

//初始化工作设备集合。
WRWorkDeviceCollection::WRWorkDeviceCollection(const WRArray<WRWorkDriver*>& drivers)
{
    typedef QList<WRWorkDevice*> List;
    typedef QHash<QUuid, List*> Hash;

    Hash hash;
    List allList;
    for(WRu i = 0; i < drivers.count(); ++i)
    {
        WRWorkDriver* driver = drivers[i];
        for(WR32s j = 0; j < driver->count(); ++j)
        {
            WRWorkDevice* device = driver->index(j);
            allList.append(device);
            WRType* type = device->type();
            while(type)
            {
                Hash::ConstIterator iter = hash.find(type->uuid());
                if (iter != hash.end())
                {
                    List* list = iter.value();
                    list->append(device);
                }
                else
                {
                    List* list = new List();
                    list->append(device);
                    hash.insert(type->uuid(), list);
                }
                type = type->base();
            }
        }
    }
    if (hash.count())
    {
        WRArray<Entry> array(hash.count() + 1);
        array[0] = Entry(QUuid(), WRArray<WRWorkDevice*>(allList));
        WRu index = 1;
        for(QHash<QUuid, List*>::Iterator iter = hash.begin(); iter != hash.end(); iter++, ++index)
        {
            List* list = iter.value();
            array[index] = Entry(iter.key(), WRArray<WRWorkDevice*>(*list));
            delete list;
        }
        m_array = array;
    }
}

//获取指定类型的对象集合。
const WRArray<WRWorkDevice*>& WRWorkDeviceCollection::filter(const QUuid& tuid) const
{
    for(WRu i = 0, l = m_array.count(); i < l; ++i)
    {
        const Entry& entry = m_array[i];
        if (entry.uuid() == tuid)
        {
            return entry.data();
        }
    }
    return WRArray<WRWorkDevice*>::empty();
}
